package cn.com.hp.feature.util;

import cn.com.hp.feature.containt.BaseStatus;
import cn.com.hp.feature.exception.ServiceException;
import cn.com.hp.feature.response.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.security.SecureRandom;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @ClassName ToolUtil
 * @Description
 * @Date 2020/11/3 19:49
 */
@Slf4j
public class ToolUtil {

    public static final Logger logger = LoggerFactory.getLogger(ToolUtil.class);

    public static final String FORMAT = "yyyy-MM-dd HH:mm:ss";

    public static final String FMT = "yyyyMMdd";

    public static final String DAY = "yyyy-MM-dd";

    public static final String MONTH = "yyyy-MM";
    public static final String EN_FORMAT = "MMM dd,yyyy";

    //FWD_SECRET进行base64加密之后得到AES加密的key
    public static final String SECRET_KEY = "RldEX1NFQ1JFVA==";

    /**
     * 日期校验
     */
    public static final String PREFIX = "^((19|20)[0-9][0-9]-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)$";

    /**
     * 时间校验，带空格
     */
    public static final String SUFFIX = "^ (([0-2][0-3])|([0-1][0-9])):[0-5][0-9]:[0-5][0-9]$";

    /**
     * 月份校验
     */
    public static final String MONTH_FORMAT = "^((19|20)[0-9][0-9])-(0[123456789]|1[012])$";

    /**
     * 判断字符串为空（null或者""）
     *
     * @param s
     * @return
     */
    public static boolean isEmpty(String s) {
        return s == null || s.length() == 0;
    }

    /**
     * 判断字符串不为空（null或者""）
     *
     * @param s
     * @return
     */
    public static boolean isNotEmpty(String s) {
        return !isEmpty(s);
    }

    /**
     * 判断List为空（null或者[]）
     *
     * @param list
     * @return
     */
    public static boolean isEmpty(List<?> list) {
        return list == null || list.isEmpty();
    }

    /**
     * 判断List不为空（null或者[]）
     *
     * @param list
     * @return
     */
    public static boolean isNotEmpty(List<?> list) {
        return !isEmpty(list);
    }

    /**
     * 日期校验
     *
     * @param date
     * @return
     */
    public static boolean verify(String date, String format) {
        if (isNotEmpty(format)) {
            switch (format) {
                case FORMAT:
                    return verify(date);
                case DAY:
                    return Pattern.matches(PREFIX, date);
                case MONTH:
                    return Pattern.matches(MONTH_FORMAT, date);
                default:
                    return false;
            }
        }
        return false;
    }

    /**
     * 日期校验
     *
     * @param date
     * @return
     */
    public static boolean verify(String date) {
        int length = 19;
        if (date.length() == length) {
            return Pattern.matches(PREFIX, date.substring(0, 10)) && Pattern.matches(SUFFIX, date.substring(10, length));
        }
        return false;
    }

    /**
     * date To Str
     *
     * @param date
     * @return
     */
    public static String dateToStr(Date date) {
        return dateToStr(date, FORMAT);
    }

    /**
     * date To Str
     *
     * @param date
     * @return
     */
    public static String dateToStr(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        return format.format(date);
    }

    /**
     * date To Str
     *
     * @param date
     * @return
     */
    public static String dateToEnStr(Date date, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern,Locale.ENGLISH);
        return format.format(date);
    }

    public static Date strToDate(String str) {
        return strToDate(str, FORMAT);
    }

    public static Date strToDate(String str, String pattern) {
        SimpleDateFormat format = new SimpleDateFormat(pattern);
        Date date = null;
        try {
            date = format.parse(str);
        } catch (ParseException e) {
            logger.error("日期转换错误", e);
        }
        return date;
    }


    /**
     * List<T> 转 str,str
     *
     * @param list
     * @return
     */
    public static String getSplitStr(List<String> list) {
        String str = "";
        if (ToolUtil.isNotEmpty(list)) {
            for (int i = 0; i < list.size(); i++) {
                if (i == list.size() - 1) {
                    str += list.get(i);
                } else {
                    str += list.get(i) + ",";
                }
            }
        }
        return str;
    }

    /**
     * 获取[,]截取的第一个字符
     *
     * @param str
     * @return
     */
    public static String getSplitFirst(String str) {
        return str != null ? str.split(",")[0] : null;
    }

    /**
     * 对象转Map
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = obj.getClass();
        System.out.println(clazz);
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            if (value != null) {
                map.put(fieldName, value);
            }
        }
        return map;
    }

    public static String createId() {
        return UUID.randomUUID().toString().replace("-", "");
    }

    public static String createSubscribeCode(String bcCode) {
        try {
            SecureRandom r = new SecureRandom();
            // 通过对象方法获取随机数
            int number = r.nextInt(9000000);
            return "FWD"+ number+bcCode;
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }



    /**
     * 比较时间是否在时间段内(包含等于)
     *
     * @return true在时间段内，false不在时间段内
     */
    public static boolean dateBetween(Date nowTime, Date beginTime, Date endTime) {
        Calendar date = Calendar.getInstance();
        date.setTime(nowTime);

        Calendar begin = Calendar.getInstance();
        begin.setTime(beginTime);

        Calendar end = Calendar.getInstance();
        end.setTime(endTime);

        if ((date.after(begin) && date.before(end)) || date.equals(begin) || date.equals(end)) {
            return true;
        } else {
            return false;
        }
    }


}

